import { defineStore } from 'pinia'

export const useAddressStore = defineStore('address', {
  state: () => ({
    addresses: [], // 存储所有地址
    defaultAddressId: null // 默认地址ID
  }),

  getters: {
    // 获取默认地址
    defaultAddress: (state) => {
      return state.addresses.find(addr => addr.id === state.defaultAddressId) ||
             state.addresses[0] || null
    }
  },

  actions: {
    // 初始化：从localStorage加载数据
    init() {
      const savedAddresses = localStorage.getItem('addresses')
      const savedDefaultId = localStorage.getItem('defaultAddressId')

      if (savedAddresses) {
        this.addresses = JSON.parse(savedAddresses)
      }

      if (savedDefaultId) {
        this.defaultAddressId = savedDefaultId
      }
    },

    // 保存地址（新增或更新）
    saveAddress(address) {
      // 生成唯一ID
      if (!address.id) {
        address.id = Date.now().toString()
        this.addresses.push(address)
      } else {
        // 更新已有地址
        const index = this.addresses.findIndex(addr => addr.id === address.id)
        if (index !== -1) {
          this.addresses[index] = address
        }
      }

      // 保存到localStorage
      this.persist()
      return address.id
    },

    // 设置默认地址
    setDefaultAddress(id) {
      this.defaultAddressId = id
      this.persist()
    },

    // 删除地址
    deleteAddress(id) {
      this.addresses = this.addresses.filter(addr => addr.id !== id)

      // 如果删除的是默认地址，重新设置默认地址
      if (this.defaultAddressId === id) {
        this.defaultAddressId = this.addresses[0]?.id || null
      }

      this.persist()
    },

    // 获取单个地址
    getAddressById(id) {
      return this.addresses.find(addr => addr.id === id) || null
    },

    // 持久化到localStorage
    persist() {
      localStorage.setItem('addresses', JSON.stringify(this.addresses))
      localStorage.setItem('defaultAddressId', this.defaultAddressId)
    }
  }
})
